window.addEventListener("load", () => {
    "use strict";

    if (!CSS.supports("clip-path", "circle(120px at center)") && !CSS.supports("-webkit-clip-path", "circle(120px at center)")) {
        document.getElementById("stage").innerHTML = '<img src="../assets/screenshot-1.png">';
        return;
    }

    var apiPath = "https://live2d.fghrsh.net/api",
        state = 0,
        modelId = localStorage.getItem("modelId"),
        modelTexturesId = localStorage.getItem("modelTexturesId");
    if (modelId === null) {
        modelId = 1;
        modelTexturesId = 53;
    }
    loadModel(modelId, modelTexturesId);

    function loadModel(modelId, modelTexturesId) {
        localStorage.setItem("modelId", modelId);
        if (modelTexturesId === undefined) modelTexturesId = 0;
        localStorage.setItem("modelTexturesId", modelTexturesId);
        loadlive2d("live2d", `${apiPath}/get/?id=${modelId}-${modelTexturesId}`, null);
        console.log("live2d", `模型 ${modelId}-${modelTexturesId} 加载完成`);
        setTimeout(() => {
            coverPosition("80%");
            state = 2;
        }, 2000);
    }

    function loadRandModel() {
        var modelId = localStorage.getItem("modelId"),
            modelTexturesId = localStorage.getItem("modelTexturesId");
        fetch(`${apiPath}/rand_textures/?id=${modelId}-${modelTexturesId}`)
            .then(response => response.json())
            .then(result => {
                loadModel(modelId, result.textures.id);
                setTimeout(() => {
                    state = 2;
                    coverPosition("80%");
                    document.getElementById("refresh").setAttribute("href", "javascript:refresh()");
                }, 1000);
            });
    }

    function loadOtherModel() {
        var modelId = localStorage.getItem("modelId");
        fetch(`${apiPath}/switch/?id=${modelId}`)
            .then(response => response.json())
            .then(result => {
                loadModel(result.model.id);
            });
    }

    function coverPosition(pos) {
        document.getElementById("cover").style.bottom = pos;
    }

    window.info = function () {
        fetch("https://v1.hitokoto.cn")
            .then(response => response.json())
            .then(result => {
                alert("点我干嘛呀`(•́へ•́╬)");
            });
    }

    window.refresh = function () {
        state = 0;
        document.getElementById("text").innerHTML = "<span style=\"color: cyan;\">巴啦啦能量</span><br><span style=\"color: white;\">#变身$</span>";
        coverPosition("10%");
        document.getElementById("refresh").setAttribute("href", "javascript:void(0)");
        setTimeout(loadRandModel, 1000);
    }

    document.getElementById("handle").addEventListener("click", () => {
        if (state === 1) {
            state = 2;
            document.getElementById("text").innerHTML = "<span style=\"color: cyan;\">H</span><span style=\"color: white;\">+</span>";
            coverPosition("80%");
        } else if (state === 2) {
            state = 1;
            document.getElementById("text").innerHTML = "<span style=\"color: cyan;\">隐藏自己</span><br><span style=\"color: white;\">(*/ω＼*)</span>";
            coverPosition("20%");
        }
    });

    document.querySelector("input[type=password]").addEventListener("focus", () => {
        if (state === 2) {
            state = 1;
            document.getElementById("text").innerHTML = "<span style=\"color: cyan;\">捂眼睛</span><br><span style=\"color: white;\">(*/ω＼*)</span>";
            coverPosition("20%");
        }
    });
    document.querySelector("input[type=password]").addEventListener("blur", () => {
        if (state === 1) {
            state = 2;
            document.getElementById("text").innerHTML = "<span style=\"color: cyan;\">H</span><span style=\"color: white;\">+</span>";
            coverPosition("80%");
        }
    });
});

// 首页图片
{
    var characterImgs = ["imgs/character1.png", "imgs/character2.png", "imgs/character3.png", "imgs/character4.png", "imgs/character5.png",
        "imgs/character6.png", "imgs/character7.png", "imgs/character8.png", "imgs/character9.png", "imgs/character10.png",
        "imgs/character11.png", "imgs/character12.png", "imgs/character13.png", "imgs/character14.png", "imgs/character15.png", "imgs/character16.png"];
    var characterJson = ["https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json", "https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json",
        "https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json", "https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json",
        "https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json", "https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json",
        "https://unpkg.com/live2d-widget-model-hijiki@1.0.5/assets/hijiki.model.json", "https://unpkg.com/live2d-widget-model-z16@1.0.5/assets/z16.model.json",
        "https://cdn.jsdelivr.net/npm/live2d-widget-model-wanko@1.0.5/assets/wanko.model.json", "https://unpkg.com/live2d-widget-model-tsumiki@1.0.5/assets/tsumiki.model.json",
        "https://unpkg.com/live2d-widget-model-unitychan@1.0.5/assets/unitychan.model.json", "https://unpkg.com/live2d-widget-model-nito@1.0.5/assets/nito.model.json",
        "https://unpkg.com/live2d-widget-model-ni-j@1.0.5/assets/ni-j.model.json", "https://unpkg.com/live2d-widget-model-nico@1.0.5/assets/nico.model.json",
        "https://unpkg.com/live2d-widget-model-nipsilon@1.0.5/assets/nipsilon.model.json",
        "https://unpkg.com/live2d-widget-model-hibiki@1.0.5/assets/hibiki.model.json"];
    var index = 0;
    var characterJsonFinl = characterJson[index];

    function leftChange() {
        if (index == 0) {
            return;
        }
        index--;
        $("#characterImg").attr("src", characterImgs[index]);
        characterJsonFinl = characterJson[index];
    }

    function rightChange() {
        if (index == characterImgs.length) {
            return;
        }
        index++;
        $("#characterImg").attr("src", characterImgs[index]);
        characterJsonFinl = characterJson[index];
    }

    function btnHidden() {
        $(".btnHide").css("display", "none");
    }

    function backHidden() {
        $(".btnBack").css("display", "block");
    }
}

{

    // 注册 和 登录
    window.onload = function ()
    {
        //如果token存在，就进行token登录
        if(window.localStorage.mkdir_fbi_bb===""||window.localStorage.mkdir_fbi_bb===undefined)
        {
            return;
        }
        //token登录
        $.ajax({
            type: "post",
            url: "/u_login_token",
            //取出本地的token传给后端进行校验
            data: {"token": window.localStorage['mkdir_fbi_bb']},
            success: function (res) {
                //令牌错误
                if (res.status != "handle_success") {
                    //清空本地令牌
                    window.localStorage['mkdir_fbi_bb'] = "";
                    return;
                } else if (res.status === "user_no_right") {
                    cocoMessage.error(3000, "当前账号已经被封禁,如有异议,请联系管理员解封", function () {
                        //回调函数
                    });
                    //账号失效，留在当前页不动
                    window.localStorage['mkdir_fbi_bb'] = "";
                    return;
                }
                //成功，直接跳到主页
                window.location.assign("to_index")
            }
        });
    }

    //标记获取验证码步骤是否成功
    var r_get_code_flag=false;
    var r_code="";//注册验证码
    function getRegisterCode() {
        //发送验证码
        let email = $("#uemail").val();
        if(email===""||email===undefined)
        {
            cocoMessage.error(3000, "发送验证码前，请先填写正确的邮箱号", function () {
                //回调函数
            });
            return;
        }
        settime();
        $.ajax({
            type: "post",
            url: "/u_register_code",
            dataType: "json",
            data: {
                'email': email
            },
            success: function (res) {
                if(res.status==="handle_success")
                {
                    r_code = res.data;
                    r_get_code_flag = true;
                    cocoMessage.info(3000, "验证码发送成功，请查收", function () {
                    });
                }
                else if(res.status==="mail_error")
                {
                    cocoMessage.error(3000, "邮箱填写有误，请检查是否已经注册过，或者是否是填写错误", function () {
                    });
                }
                else if(res.status==="mail_format_error")
                {
                    cocoMessage.error(3000, "邮箱格式不符合规范，请重新填写", function () {
                    });
                }
                else
                {
                    cocoMessage.error(3000, "邮箱发送失败，请检查是否是邮箱填写错误!", function () {
                    });
                }
            }
        });
    }

    // 注册
    function userRegister() {
        //当前用户重复注册
        if (window.localStorage.isRepeat !== undefined) {
            cocoMessage.error(3000, "您已经注册过一个账号，请不要重复注册", function () {
                //回调函数
            });
            return;
        }

        let uname = $("#uname").val();
        let upwd = $("#upwd").val();
        let virtualImgs = characterJsonFinl;
        let uemail = $("#uemail").val();
        let code = $("#code").val();
        if (uname === "" || upwd === "" || virtualImgs === "" || uemail === "") {
            cocoMessage.error(3000, "请将信息输入完整", function () {
                //回调函数
            });
            return;
        }

        let sexno = 1;
        let sex = $("#sex").val();
        if (sex === "男") {
            sexno = 1;
        } else if (sex === "女") {
            sexno = 0;
        } else {
            cocoMessage.error(3000, "输入的性别不对，请重新输入！", function () {
                //回调函数
            });
            return;
        }


        //验证码步骤出了问题
        if(!r_get_code_flag)
        {
            cocoMessage.error(3000, "验证码有误，请重新填写", function () {
            });
            return;
        }

        //检验验证码输入的和发送的是否一致
        if(r_code!=code)
        {
            cocoMessage.error(3000, "验证码输入错误，请重新输入！", function () {
                //回调函数
            });
         return;
        }

        $.ajax({
            type: "post",
            url: "/u_register",
            dataType: "json",
            data: {
                'upwd': upwd,
                'uname': uname,
                'virtualImgs': virtualImgs,
                'sex': sexno,
                'mail': uemail,
                'code': code
            },
            success: function (res) {
                //注册成功
                if (res.status == "handle_success") {
                    //保存当前用户已经注册过的信息
                    window.localStorage.isRepeat = "registered";
                    //保存token
                    window.localStorage['mkdir_fbi_bb'] = res.data;
                    //保存用户名
                    window.localStorage['uname'] = uname;
                    //跳转到主页
                    window.location.assign("to_index")
                } else if (res.status == "register_repeat") {
                    cocoMessage.error(3000, "用户名重复，请重新注册！", function () {

                    });
                } else if (res.status === "mail_repeat") {
                    cocoMessage.error(3000, "当前邮箱已经绑定了一个账号，无法继续注册!", function () {

                    });
                } else if (res.status === "mail_format_error") {
                    cocoMessage.error(3000, "qq邮箱格式有误!", function () {

                    });
                }
                else if(res.status === "code_error")
                {
                    cocoMessage.error(3000, "验证码错误,请重新填写", function () {

                    });
                }
                else
                {
                    cocoMessage.error(3000, "注册失败，请重试！", function () {

                    });
                }
            }
        });
    }

    // 登录
    function userLogin() {
        let mkdir_fbi_bb = window.localStorage.mkdir_fbi_bb;
        let uname = $("#username").val();
        let upwd = $("#password").val();
        $.ajax({
            type: "post",
            url: "/u_login_account",
            dataType: "json",
            data: {
                'uname': uname,
                'upwd': upwd
            },
            success: function (res) {
                if (res.status === "handle_success") {
                    //保存token到本地
                    //保存token
                    window.localStorage['mkdir_fbi_bb'] = res.data;
                    //保存用户名
                    window.localStorage['uname'] = uname;
                    //跳转到主页页面
                    window.location.assign("to_index")
                } else if (res.status === "login_error") {
                    cocoMessage.error(3000, "用户名或密码错误", function () {

                    });
                } else if (res.status === "user_no_right") {
                    cocoMessage.error(3000, "当前账号已经被封禁,如有异议,请联系管理员解封", function () {

                    });
                } else {
                    cocoMessage.error(3000, "出现异常，操作失败", function () {

                    });
                }
            }
        });
    }

    //登录方式切换
    function funZh() {
        var zh = document.getElementById("login")
        zh.innerHTML = `
       <p style="font-size: 15px;"><label>账号</label><input type="text" name="uname" id="username"/></p>
                                            <p style="font-size: 15px;"><label>密码</label><input type="password" name="upwd" id="password"/></p>
                                            <p style="font-size: 15px;"><button onclick="userLogin()">登录</button></p>`
    }

    function funEmail() {
        var mail = document.getElementById("login")
        mail.innerHTML = `
        <label>邮箱账号</label>
        <input type="text" id="uremail"/>
        <label>验证码</label>
        <input type="text" id="code"/>
        <input type="button" id="lay" onclick="getCode()" value="获取验证码">
        <p style="font-size: 15px;"><button onclick="userLoginByEmail()">登录</button></p>
        `
    }

    //标记获取验证码步骤是否成功
    var get_code_flag=false;

    //计时器
    function settime() {
        if (countdown == 0) {
            $("#lay").attr("disabled", false);
            $("#lay").val("获取验证码");
            countdown = 30;
        } else {
            // val.setAttribute("disabled", true);
            $("#lay").attr("disabled", true);
            // val.value = "重新发送(" + countdown + ")";
            $("#lay").val("重新发送(" + countdown + ")");
            countdown--;
            setTimeout(function () {
                settime()
            }, 1000)
        }
    }

    var countdown = 30;
    var code = '';
    function getCode()
    {
        //发送验证码
        let email = $("#uremail").val();
        if(email===""||email===undefined)
        {
            cocoMessage.error(3000, "发送验证码前，请先填写正确的邮箱号", function () {
                //回调函数
            });
            return;
        }
        settime();
        $.ajax({
            type: "post",
            url: "/u_send_code",
            dataType: "json",
            data: {
                'email': email
            },
            success: function (res)
            {
                if(res.status==="handle_success")
                {
                    code = res.data;
                    get_code_flag = true;
                    cocoMessage.info(3000, "验证码发送成功，请查收", function () {
                    });
                }
                else if(res.status==="mail_error")
                {
                    cocoMessage.error(3000, "邮箱填写有误，请检查是否已经注册过，或者是否是填写错误", function () {
                    });
                }
                else
                {
                    cocoMessage.error(3000, "邮箱发送失败，请检查邮箱是否填写有误", function () {
                    });
                }
            }
        });
    }

    function userLoginByEmail()
    {

        let mkdir_fbi_bb = window.localStorage.mkdir_fbi_bb;
        let uemail = $("#uremail").val();
        let u_code=$("#code").val();

        //验证码步骤出了问题
        if(!get_code_flag)
        {
            cocoMessage.error(3000, "验证码有误，请重新填写", function () {
            });
            return;
        }


         if(u_code!=code)
         {
             cocoMessage.error(3000, "验证码有误，请重新填写", function () {
             });
             return;
         }



        $.ajax({
            type: "post",
            url: "/u_login_email",
            dataType: "json",
            data: {
                'email': uemail,
                'code': u_code
            },
            success: function (res)
            {
                // console.log(res)
                //验证没有问题
                if(res.status==="handle_success")
                {
                    //保存token到本地
                    //保存token
                    window.localStorage['mkdir_fbi_bb'] = res.data[0];
                    //保存用户名
                    window.localStorage['uname'] = res.data[1];
                    //跳转到主页页面
                    window.location.assign("to_index")
                }
                else if(res.status==="user_no_right")
                {
                    cocoMessage.error(3000, "当前账号已经被封禁,如有异议,请联系管理员解封", function () {
                    });
                }
                else if(res.status==="code_expired")
                {
                    cocoMessage.error(3000, "验证码过期，请重新获取", function () {
                    });
                }
                else if(res.status==="code_error")
                {
                    cocoMessage.error(3000, "验证码错误", function () {
                    });
                }
                else
                {
                    cocoMessage.error(3000, "出现异常，请重新尝试", function () {
                    });
                }
            }
        });
    }
}